package org.pidan.basic.designModel.agency.CGLIB;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * {@code @description}: 代理主要类
 * {@code @author}: huangyuxin
 * {@code @date}: 2023-11-16
 */
public class CglibProxy implements MethodInterceptor {

    private Object object;

    // 这里的目标类型为Object，则可以接受任意一种参数作为被代理类，实现了动态代理
    public Object getInstance(Object o) {

        // 设置需要创建子类的类
        this.object = o;
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(o.getClass());
        enhancer.setCallback(this);
        return enhancer.create();
    }

    //代理实际方法
    @Override
    public Object intercept(Object obj, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {

        System.out.println("cglib 开始事务");
        Object invoke = methodProxy.invoke(object, objects);
        System.out.println("cglib 结束事务");
        // 返回代理对象
        return invoke;
    }
}
